package com.example.demo03_mvm.viewmodel;

import android.app.Application;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.SavedStateHandle;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.blankj.utilcode.util.ToastUtils;
import com.example.demo03_mvm.R;
import com.example.demo03_mvm.adapter.CartAdapter;
import com.example.demo03_mvm.databinding.FragmentCartBinding;
import com.example.demo03_mvm.model.AddCartEntity;
import com.example.demo03_mvm.model.CartEntity;
import com.example.demo03_mvm.repos.CartRepso;
import com.example.demo03_mvm.utils.LoginCheck;
import com.google.gson.Gson;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class CartViewModel extends BaseViewModel {
    CartRepso cartRepso;
    CartAdapter adapter;
    int num = 0;//总价
    int count =0;
    public CartViewModel(@NonNull Application application) {
        super(application);
        cartRepso = new CartRepso();
    }

    //@LoginCheck
    public void getCarts(LifecycleOwner owner, CartAdapter adapter) {
        this.adapter = adapter;
        cartRepso.getCarts().observe(owner, new Observer<CartEntity>() {
            @Override
            public void onChanged(CartEntity cartEntity) {
                adapter.getData().addAll(cartEntity.getData());
                adapter.notifyDataSetChanged();
                //Log.i("===", "size:" + adapter.getData().size());
            }
        });
    }

    /**
     * 全选反选
     *
     * @param b 全选是否选中
     */
    public void checkedAll(boolean b, TextView tvMoney,TextView btn) {

        num=0;
        count=0;
        List<CartEntity.DataBean> data = adapter.getData();
        if(b){
            count= data.size();
        }else{
            count=0;
        }
        btn.setText("去结算（"+count+"）");
        for (int i = 0; i < data.size(); i++) {
//            CheckBox cb = (CheckBox) adapter.getViewByPosition(i, R.id.cb);
//            cb.setChecked(b);
            data.get(i).setChecked(b);
            if (b) {
                Log.d("===", "checkedAll: "+count);
//                EditText et=(EditText) adapter.getViewByPosition(i,R.id.c_num);
//                int s = Integer.parseInt(et.getText().toString());

                num += data.get(i).getCount()* data.get(i).getGoods_default_price();//每行的总价
            }else{
                Log.d("===", "checkedAll: "+count);
            }
        }
        adapter.notifyDataSetChanged();
        tvMoney.setText(String.valueOf(num));
    }

    public void itemCheck(EditText et,int position, CheckBox allchange, TextView tvMoney, TextView btn) {
        List<CartEntity.DataBean> data = adapter.getData();
//        int s = Integer.parseInt(et.getText().toString());
        int s=data.get(position).getCount();
        CheckBox cb = (CheckBox) adapter.getViewByPosition(position, R.id.cb);
        data.get(position).setChecked(cb.isChecked());
        adapter.notifyDataSetChanged();
        if (!cb.isChecked()) {
            allchange.setChecked(false);
            count--;
            num -= s * data.get(position).getGoods_default_price();//每行的总价
        } else {
            num = 0;
            int n = 0;//1.2.
            count=0;
            for (int i = 0; i < data.size(); i++) {
//                CheckBox cb2 = (CheckBox) adapter.getViewByPosition(i, R.id.cb);
                if (!data.get(i).isChecked()) {
                    n = 1;//1.
                    allchange.setChecked(false);
                } else {
                    //n++;//2.
                    count ++;
                    num +=s * data.get(i).getGoods_default_price();//每行的总价
                }
            }
            if (n == 0) {
                allchange.setChecked(true);
            }
        }

        tvMoney.setText(String.valueOf(num));
        //Log.i("====", "itemCheck: "+count);
        btn.setText("去结算（"+count+"）");
    }

    public void add(EditText et,int pos,boolean b, TextView tvMoney){
        String s = et.getText().toString();
        String s1 = String.valueOf(Integer.parseInt(s) + 1);
        et.setText(s1);
        if(b){
            num+=adapter.getData().get(pos).getGoods_default_price();
            tvMoney.setText(String.valueOf(num));
        }
        adapter.getData().get(pos).setCount(Integer.parseInt(s1));
        adapter.notifyDataSetChanged();
    }

    public void del(EditText et,int pos,boolean b, TextView tvMoney){
        int s = Integer.parseInt(et.getText().toString());
        if(s>1) {
            String s1 = String.valueOf(s - 1);
            et.setText(s1);
            if(b){
                num-=adapter.getData().get(pos).getGoods_default_price();
                tvMoney.setText(String.valueOf(num));
            }
            adapter.getData().get(pos).setCount(Integer.parseInt(s1));
            adapter.notifyDataSetChanged();
        }else{
            ToastUtils.showLong("购买数不能小于1");
        }
    }

    public void deleleCart(LifecycleOwner owner,int n){
        String s;
        if(n==0) {
            //{"ids":"2,14,16"}
             StringBuilder sb = new StringBuilder();
            for (int i = 0; i < adapter.getData().size(); i++) {
                //CheckBox cb=(CheckBox) adapter.getViewByPosition(i,R.id.cb);
                if (adapter.getData().get(i).isChecked()) {
                    sb.append(adapter.getData().get(i).getId() + ",");
                }
            }
            s = sb.substring(0, sb.length() -1);
        }else{
            s=String.valueOf(n);
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("ids", s);
        String json = new Gson().toJson(map);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        cartRepso.deleteCart(body).observe(owner, new Observer<AddCartEntity>() {
            @Override
            public void onChanged(AddCartEntity addCartEntity) {
                adapter.getData().clear();
                getCarts(owner,adapter);
            }
        });
    }

    /*public void pay(MyPay myPay,View v){
        myPay.pay(v,String.valueOf(num));
    }*/


}
